<script setup lang="ts">
  import { ref } from 'vue'
  import { usePushOrderToDianJiangYuan } from '@/services/pages/order/useOrder'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { pushLoading: dianJiangYuanPushLoaidng, push: dianJiangYuanPush } =
    usePushOrderToDianJiangYuan()

  defineOptions({
    name: 'OrderPushModal',
  })

  const props = defineProps({
    orderId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 推送目标下拉选项
  const pushPlatformOptions = [{ label: '电匠院', value: 'dian_jiang_yuan' }]

  // 推送平台
  const pushPlatform = ref<'dian_jiang_yuan' | ''>('')

  // 推送策略
  const pushStrategy = {
    dian_jiang_yuan: dianJiangYuanPush,
  }

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (!pushPlatform.value) {
      return false
    }

    try {
      const res = await pushStrategy[pushPlatform.value](props.orderId)
      if (res.code === 20000) {
        HMessage.success('推送完成')
        emits('update')
        hideDialog()
        return
      }
      HMessageBox.error(res.message)
    } catch (error) {
      HMessageBox.error('推送失败，请稍后重试')
    }
  }
</script>

<template>
  <h-dialog
    v-model="visible"
    title="工单推送"
    :loading="dianJiangYuanPushLoaidng"
    @close="hideDialog"
  >
    <el-form label-position="top" inline-message class="modal_form_content">
      <el-form-item label="推送平台">
        <el-select v-model="pushPlatform" placeholder="请选择推送平台">
          <el-option
            v-for="(pushPlatformOption, pushPlatformOptionIndex) in pushPlatformOptions"
            :key="pushPlatformOptionIndex"
            :label="pushPlatformOption.label"
            :value="pushPlatformOption.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>
